<link rel="stylesheet" type="text/css"
      href="$request.contextPath/res/assets/css/fullcalendarv2.min.css"/>

<script>
    var boId = $boId;
    var events = new Array();
    var planName = new Object();
    var plans = new Object();
    var index = 1;
    #foreach ($item in ${platforms})
        planName[${item.platformId}] = '${item.platformName}'
    #end
    #foreach ($item in ${boplans})
        events.push({
            title: planName[$!{item.platformId}],
            start: new Date('$date.format('yyyy-MM-dd HH:mm', ${item.beginTime})'),
            end: new Date('$date.format('yyyy-MM-dd HH:mm', ${item.endTime})'),
            className: 'label-success'
        });
        plans['_fc'+index++] = {
            platformId: $!{item.platformId},
            beginTime: '${item.beginTime}',
            endTime: '${item.endTime}',
            userId: boId,
            planId: ${item.planId},
            roomId:'${item.roomId}',
            roomUrl:'${item.roomUrl}'
        }
    #end
</script>

<div class="page-content">
    <div class="page-header">
        <h1>
            ${boName}播出计划
            <small>
                <i class="ace-icon fa fa-angle-double-right"></i>
                拖动添加播出计划
            </small>
        </h1>
    </div><!-- /.page-header -->

    <div class="row">
        <div class="col-xs-12">
            <!-- PAGE CONTENT BEGINS -->
            <div class="row">
                <div class="col-sm-9">
                    <div class="space"></div>
                    <div id="calendar"></div>
                </div>

                <div class="col-sm-3">
                    <div class="widget-box transparent">
                        <div class="widget-header">
                            <h4>合作直播平台</h4>
                        </div>
                        <div class="widget-body">
                            <div class="widget-main no-padding">
                                <div id="external-events">
                                    #foreach ($item in ${platforms})
                                        <div class="external-event label-success ui-draggable ui-draggable-handle" data-class="label-success" style="position: relative;">
                                        <i class="ace-icon fa fa-arrows">
                                        </i>
                                            <span id="$item.platformName" val="$item.platformId"> </span>
                                        $item.platformName
                                    </div>
                                    #end
                                    <!--label>
                                        <input type="checkbox" class="ace ace-checkbox" id="drop-remove">
                                        <span class="lbl"> </span>
                                    </label-->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- PAGE CONTENT ENDS -->
        </div><!-- /.col -->
    </div><!-- /.row -->
</div>
<script type="text/javascript" src="$request.contextPath/res/assets/js/moment.min.js"></script>
<script type="text/javascript" src="$request.contextPath/res/assets/js/fullcalendarv2.min.js"></script>
<script type="text/javascript" src="$request.contextPath/res/assets/js/lang-all.js"></script>
<script type="text/javascript" src="$request.contextPath/res/assets/js/jquery-ui.custom.js"></script>
<script type="text/javascript" src="$request.contextPath/res/assets/js/jquery.ui.touch-punch.js"></script>
<script type="text/javascript" src="$request.contextPath/res/assets/js/bootbox.js"></script>
<script type="text/javascript">
    jQuery(function($) {
        /* 初始化平台拖拽事件
        -----------------------------------------------------------------*/
        $('#external-events div.external-event').each(function() {
                    // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
                    // it doesn't need to have a start or end
                    var eventObject = {
                        title: $.trim($(this).text()) // use the element's text as the event title
                    };
                    // store the Event Object in the DOM element so we can get to it later
                    $(this).data('eventObject', eventObject);
                    // make the event draggable using jQuery UI
                    $(this).draggable({
                        zIndex: 999,
                        revert: true,      // will cause the event to go back to its
                        revertDuration: 0  //  original position after the drag
                    });
                });
                /* initialize the calendar
                 -----------------------------------------------------------------*/
                var date = new Date();
                var d = date.getDate();
                var m = date.getMonth();
                var y = date.getFullYear();
                var calendar = $('#calendar').fullCalendar({
                    //isRTL: true,
                    buttonHtml: {
                        prev: '<i class="ace-icon fa fa-chevron-left"></i>',
                        next: '<i class="ace-icon fa fa-chevron-right"></i>'
                    },
                    timezone:'local',
                    defaultView:'agendaWeek',
                    header: {
                        left: 'prev,next today',
                        center: 'title',
                        right: 'month,agendaWeek,agendaDay'
                    },
                    events: events,
                    editable: true,
                    droppable: true, // this allows things to be dropped onto the calendar !!!
                    drop: function(date, allDay) {
                        console.log("====drop====");
                        var originalEventObject = $(this).data('eventObject');
                        var $extraEventClass = $(this).attr('data-class');
                        // we need to copy it, so that multiple events don't have a reference to the same object
                        var copiedEventObject = $.extend({}, originalEventObject);
                        // assign it the date that was reported
                        copiedEventObject.start = date;
                        copiedEventObject.allDay = allDay;
                        console.log(copiedEventObject);
                        addBoplan(copiedEventObject.start._d, copiedEventObject.title);
                        if($extraEventClass) copiedEventObject['className'] = [$extraEventClass];
                        // render the event on the calendar
                        // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
                        $('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
                        // is the "remove after drop" checkbox checked?
                        if ($('#drop-remove').is(':checked')) {
                            // if so, remove the element from the "Draggable Events" list
                            $(this).remove();
                        }
                    },
                    selectable: true,
                    selectHelper: true,
                    select: function(start, end, allDay) {
                        /*console.log("select");
                        console.log(allDay);
                        bootbox.prompt("New Event Title:", function(title) {
                            if (title !== null) {
                                calendar.fullCalendar('renderEvent',
                                        {
                                            title: title,
                                            start: start,
                                            end: end,
                                            allDay: allDay,
                                            className: 'label-info'
                                        },
                                        true // make the event "stick"
                                );
                            }
                        });
                        calendar.fullCalendar('unselect');*/
                    },
                    eventClick: function(calEvent, jsEvent, view) {
                        console.log("eventClick");
                        console.log(calEvent);
                        console.log(view);
                        //display a modal
                        var modal =
                                '<div class="modal fade">\
                                  <div class="modal-dialog">\
                                   <div class="modal-content">\
                                     <div class="modal-body">\
                                       <button type="button" class="close" data-dismiss="modal" style="margin-top:-10px;">&times;</button>\
                                       <div class="form-group"><label >房间信息:</label>\
					  <input id="roomId" name="roomId" style="width:400px;" type="text" value="'+ plans[calEvent._id].roomId  +'" class="form-control" placeholder="直播平台房间号" /></div><div class="space-4"></div>\
					  <div class="form-group"><label >直播地址:</label>\
					  <input id="roomUrl" name="roomUrl"  style="width:400px;" value="'+ plans[calEvent._id].roomUrl  +'" type="text" class="form-control" placeholder="直播平台房间地址"/></div><div class="space-4"></div>\
					 <button type="button" style="float:right; margin-top:-53px; padding-right:20px;"class="btn btn-sm btn-success" data-action="save"><i class="ace-icon fa fa-check"></i>保存</button>\
				 </div>\
				 <div class="modal-footer">\
					<button type="button" class="btn btn-sm btn-danger" data-action="delete"><i class="ace-icon fa fa-trash-o"></i> 删除</button>\
					<button type="button" class="btn btn-sm" data-dismiss="modal"><i class="ace-icon fa fa-times"></i> 取消</button>\
				 </div>\
			  </div>\
			 </div>\
			</div>';
                        var modal = $(modal).appendTo('body');
                        modal.find('form').on('submit', function(ev){
                            ev.preventDefault();
                            calEvent.title = $(this).find("input[type=text]").val();
                            calendar.fullCalendar('updateEvent', calEvent);
                            modal.modal("hide");
                        });
                        modal.find('button[data-action=delete]').on('click', function() {
                            calendar.fullCalendar('removeEvents' , function(ev){
                                removeBoplan(ev._id);
                                return (ev._id == calEvent._id);
                            })
                            modal.modal("hide");
                        });
                        modal.find('button[data-action=save]').on('click', function() {
                            saveRoomInfo(calEvent._id, $("#roomId").val(), $("#roomUrl").val());
                            modal.modal("hide");
                        });
                        modal.modal('show').on('hidden', function(){
                            modal.remove();
                        });
                    },
                    eventDrop:function(event, jsEvent, ui, view) {
                       if(event.start && event.end) {
                            changePlan(event._id, event.start._d, event.end._d);
                        } else {
                            changePlan(event._id, event.start._d, null);
                        }
                    },
                    eventResize:function( event, delta, revertFunc, jsEvent, ui, view ) {
                        if(event.start && event.end) {
                            changePlan(event._id, event.start._d, event.end._d);
                        } else {
                            changePlan(event._id, event.start._d, null);
                        }
                    },
                });
            })

    function addBoplan(date,content) {
        console.log("addBoplan"+date);
        var beginDate = date;
        beginDate.setHours(0);
        beginDate.setMinutes(0);
        var endDate = date;
        endDate.setHours(11);
        endDate.setMinutes(59);
        var obj = {
            platformId : $("#"+$.trim(content)).attr("val"),
            beginTime : date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" 01:00:00",
            endTime : date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" 23:00:00",
            userId : boId,
            planId : 0,
            roomId : "",
            roomUrl: "",
        }
        $.ajax({
            type: "GET",
            url: './bobo/AddBoboPlan',
            data: obj,
            success: function (data) {
                console.log(data);
                plans['_fc'+index++] = data;
                console.log(plans);
            },
            dataType: 'JSON'
        });
    }

    function saveRoomInfo(id, roomId, roomUrl) {
        var obj = plans[id];
        obj.roomId = roomId;
        obj.roomUrl = roomUrl;
        console.log(obj);
        $.ajax({
            type: "POST",
            url: './bobo/SaveBoboPlan',
            data: {
                'planId':obj.planId,
                'roomId':roomId,
                'roomUrl':roomUrl,
            },
            success: function (data) {
                plans[id] = data;
            },
            dataType: 'JSON'
        });
    }

    function changePlan(ts,beginTime,endTime) {
        var obj = plans[ts];
        console.log("changePlan")
        console.log(obj);
        console.log(ts)
        obj.beginTime = beginTime.getFullYear()+"-"+(beginTime.getMonth()+1)+"-"+beginTime.getDate()+" "+beginTime.getHours()+":"+beginTime.getMinutes()+":"+beginTime.getSeconds();
        if(endTime) {
            obj.endTime = endTime.getFullYear()+"-"+(endTime.getMonth()+1)+"-"+endTime.getDate()+" "+endTime.getHours()+":"+endTime.getMinutes()+":"+endTime.getSeconds();
        } else {
            obj.endTime = beginTime.getFullYear()+"-"+(beginTime.getMonth()+1)+"-"+beginTime.getDate()+" 22:00:00";
        }
        plans[ts] = obj;
        $.ajax({
            type: "GET",
            url: './bobo/SaveBoboPlan',
            data: obj,
            success: function (data) {
                plans[ts] = data;
                console.log(plans)
            },
            dataType: 'JSON'
        });
    }

    function removeBoplan(ts) {
        console.log(ts);
        $.ajax({
            type: "GET",
            url: './bobo/DelBoboPlan',
            data: {planId:plans[ts]['planId']},
            success: function (data) {
                delete plans[ts];
            },
            dataType: 'JSON'
        });
    }

</script>
